//
//  CacheSqliteTool.m
//  MomHelp
//
//  Created by xuguoyong on 16/8/16.
//  Copyright © 2016年 hudongkeji. All rights reserved.
//

#import "CacheSqliteTool.h"
#import <FMDB.h>
#import "NSFileManager+HomeDocumentPath.h"
#import "UserInfoModel.h"
@implementation CacheSqliteTool

/** 数据库实例 */
static FMDatabase *_db;

+ (void)initialize
{
    // 1.获得数据库文件路径
    NSString *faileName = [NSFileManager getOfflineCacheSqlitePath];
    SGLog(@"数据库的存放路径:%@",faileName);
    // 2.得到数据库
    _db = [FMDatabase databaseWithPath:faileName];
    
}

/**
 *  创建用户表 返回表名
 */
+ (NSString *)createUserInfoTabel
{

    if ([self isTableOK:@"t_userInfo"]) {
        return @"t_userInfo";
    }
    [_db open];
        // 4.创表
    BOOL result = [_db executeUpdate:@"CREATE TABLE IF NOT EXISTS t_userInfo (id integer PRIMARY KEY AUTOINCREMENT, access_token text NOT NULL, user_id text NOT NULL, user_dict blob NOT NULL);"];
        if (result) {
            NSLog(@"成功创表");
               return @"t_userInfo";
        }
        [_db close];
       return nil;
}

/**
 *  判断某个表是否存在
 *
 *  @param tableName 表名
 *
 *  @return
 */
+ (BOOL) isTableOK:(NSString *)tableName
{
    [_db open];
    FMResultSet *rs = [_db executeQuery:@"select count(*) as 'count' from sqlite_master where type ='table' and name = ?", tableName];
    while ([rs next])
    {
        // just print out what we've got in a number of formats.
        NSInteger count = [rs intForColumn:@"count"];
      if (0 == count)
        {
            return NO;
        }
        else
        {
            return YES;
        }
    }
     [_db close];
    return NO;
}



/**
 *  缓存用户信息到数据库中
 */
+ (void)saveHomeStatusDictArray:(NSDictionary *)user_dict accessToken:(NSString *)accessToken user_id:(NSString *)user_id
{
    //创建用户表 如果存在则不创建
    [self createUserInfoTabel];
   [_db open];
    NSData *data = [NSKeyedArchiver archivedDataWithRootObject:user_dict];
//    查询数据库中是否有这个用户的信息
    FMResultSet * rs = [_db executeQuery:@"SELECT user_id FROM t_userInfo"];
    if ([rs next]) {
        //数据库中有这个用户 更新 用户
      NSString *sql =   [NSString stringWithFormat:@"update t_userInfo set access_token = \"%@\",user_dict =  ? where user_id =%@",accessToken,user_id];
   
        [_db executeUpdate:sql data:data];
        
    }else
    {
        //数据库中没有这个用户 直接插入
      [_db executeUpdate:@"INSERT INTO t_userInfo (access_token, user_id, user_dict) VALUES (?, ?, ?);", accessToken,user_id, data];
    } 
    [_db close];
}
/**
 *  通过请求参数去数据库中加载对应的微博数据
 *
 *  @param param 请求参数
 */
+ (NSDictionary *)cachedHomeStatusesWithParam:(UserInfoModel *)model
{
    
    
    [_db open];
    // 根据请求参数查询数据
    FMResultSet *resultSet = [_db executeQuery:[NSString stringWithFormat:@"SELECT * FROM t_userInfo WHERE user_id=%@",model.user_id]];
   
    NSDictionary *statusDict =nil;
    // 遍历查询结果
    while (resultSet.next) {
        NSData *statusDictData = [resultSet objectForColumnName:@"user_dict"];
        statusDict = [NSKeyedUnarchiver unarchiveObjectWithData:statusDictData];
   
    }
     [_db close];
    return statusDict;
}
@end
